package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.annotation.NeedLogin;
import com.atguigu.tingshu.common.kafka.constant.KafkaConst;
import com.atguigu.tingshu.common.kafka.service.KafkaService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.enums.TrackStatType;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.vo.album.AlbumTrackListVo;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.album.TrackStatVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.simpleframework.xml.core.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Tag(name = "声音管理")
@RestController
@RequestMapping("api/album")
@SuppressWarnings({ "all" })
public class TrackInfoApiController {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private KafkaService kafkaService;

    @PostMapping("/trackInfo/uploadTrack")
    @Operation(tags = "上传声音")
    @NeedLogin
    public Result<Map<String, String>> uploadTrack(@RequestParam("file") MultipartFile multipartFile) {
        return Result.ok(trackInfoService.uploadTrack(multipartFile));
    }

    @PostMapping("/trackInfo/saveTrackInfo")
    @Operation(tags = "保存声音信息")
    @NeedLogin
    public Result<?> saveTrackInfo(@Validate @RequestBody TrackInfoVo trackInfoVo) {
        trackInfoService.saveTrackInfo(trackInfoVo);
        return Result.ok();
    }

    @PostMapping("/trackInfo/findUserTrackPage/{page}/{limit}")
    @Operation(tags = "查询用户声音分页")
    @NeedLogin
    public Result<Page<TrackListVo>> findUserTrackPage(@PathVariable Long page,
            @PathVariable Long limit,
            @RequestBody TrackInfoQuery trackInfoQuery) {
        return Result.ok(trackInfoService.findUserTrackPage(page, limit, trackInfoQuery));
    }

    @PutMapping("trackInfo/updateTrackInfo/{id}")
    @Operation(tags = "更新声音信息")
    @NeedLogin
    public Result<?> updateTrackInfo(@PathVariable Long id, @RequestBody TrackInfoVo trackInfoVo) {
        trackInfoService.updateTrackInfo(id, trackInfoVo);
        return Result.ok();
    }

    @DeleteMapping("trackInfo/removeTrackInfo/{id}")
    @Operation(tags = "删除声音信息")
    @NeedLogin
    public Result<?> removeTrackInfo(@PathVariable Long id) {
        trackInfoService.deleteTrackInfo(id);
        return Result.ok();
    }

    @GetMapping("trackInfo/getTrackInfo/{id}")
    @Operation(tags = "查询声音信息")
    @NeedLogin
    public Result<TrackInfoVo> getTrackInfo(@PathVariable Long id) {
        TrackInfoVo trackInfoVo = trackInfoService.getTrackInfo(id);

        // 异步更新声音播放量统计
        TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
        trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-", ""));
        trackStatMqVo.setAlbumId(trackInfoVo.getAlbumId());
        trackStatMqVo.setTrackId(id);
        trackStatMqVo.setStatType(TrackStatType.PLAY_STAT_NUM.getCode());
        trackStatMqVo.setCount(1);
        kafkaService.sendMessage(KafkaConst.TOPIC_TRACK_STAT_UPDATE, trackStatMqVo);

        return Result.ok(trackInfoVo);
    }

    /**
     * 获取声音实体信息（用于Feign调用）
     *
     * @param trackId 声音ID
     * @return 声音实体信息
     */
    @GetMapping("/trackInfo/getTrackInfoEntity/{trackId}")
    @Operation(tags = "获取声音实体信息")
    public Result<TrackInfo> getTrackInfoEntity(@PathVariable Long trackId) {
        TrackInfo trackInfo = trackInfoService.getById(trackId);
        return Result.ok(trackInfo);
    }

    /**
     * 查询专辑声音分页列表
     * 注意：此接口允许未登录用户访问，所以不使用@NeedLogin注解
     *
     * @param albumId 专辑ID
     * @param page    页码
     * @param limit   每页条数
     * @return 分页结果
     */
    @GetMapping("/trackInfo/findAlbumTrackPage/{albumId}/{page}/{limit}")
    @Operation(tags = "查询专辑声音分页列表")
    @NeedLogin
    public Result<Page<AlbumTrackListVo>> findAlbumTrackPage(@PathVariable Long albumId,
            @PathVariable Long page,
            @PathVariable Long limit) {
        Long userId = AuthContextHolder.getUserId();
        return Result.ok(trackInfoService.findAlbumTrackPage(userId, albumId, page, limit));
    }

    /**
     * 获取声音统计信息
     *
     * @param trackId 声音ID
     * @return 声音统计信息
     */
    @GetMapping("/trackInfo/getTrackStatVo/{trackId}")
    @Operation(tags = "获取声音统计信息")
    @NeedLogin
    public Result<TrackStatVo> getTrackStatVo(@PathVariable Long trackId) {
        TrackStatVo trackStatVo = trackInfoService.getTrackStatVo(trackId);
        return Result.ok(trackStatVo);
    }

    /**
     * 获取用户声音分集购买支付列表
     *
     * @param trackId 声音ID
     * @return 支付选项列表
     */
    @GetMapping("/trackInfo/findUserTrackPaidList/{trackId}")
    @Operation(tags = "获取用户声音分集购买支付列表")
    @NeedLogin
    public Result<List<Map<String, Object>>> findUserTrackPaidList(@PathVariable Long trackId) {
        Long userId = AuthContextHolder.getUserId();
        List<Map<String, Object>> result = trackInfoService.findUserTrackPaidList(userId, trackId);
        return Result.ok(result);
    }

    /**
     * 查询指定声音及之后的所有声音列表
     *
     * @param albumId  专辑ID
     * @param orderNum 起始排序号
     * @return 声音列表
     */
    @GetMapping("/trackInfo/getTracksFromOrderNum/{albumId}/{orderNum}")
    @Operation(tags = "查询指定声音及之后的所有声音列表")
    public Result<List<TrackInfo>> getTracksFromOrderNum(@PathVariable Long albumId, @PathVariable Integer orderNum) {
        LambdaQueryWrapper<TrackInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TrackInfo::getAlbumId, albumId)
                .ge(TrackInfo::getOrderNum, orderNum)
                .orderByAsc(TrackInfo::getOrderNum);
        List<TrackInfo> tracks = trackInfoService.list(queryWrapper);
        return Result.ok(tracks);
    }

    /**
     * 根据声音ID列表查询专辑ID映射
     *
     * @param trackIdList 声音ID列表
     * @return Map<声音ID, 专辑ID>
     */
    @PostMapping("/trackInfo/getAlbumIdsByTrackIds")
    @Operation(tags = "根据声音ID列表查询专辑ID映射")
    public Result<Map<Long, Long>> getAlbumIdsByTrackIds(@RequestBody List<Long> trackIdList) {
        Map<Long, Long> albumIdMap = trackInfoService.getAlbumIdsByTrackIds(trackIdList);
        return Result.ok(albumIdMap);
    }
}
